<!-- 项目合同档案 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="borrowApplyNo" required>
          <u--input v-model="model.borrowApplyNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请时间" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="propose" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择申请部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="签订公司" prop="applyCompany" required>
          <h-select-company-input
            style="width: 100%"
            v-model="model.applyCompany"
            border="surround"
            placeholder="请选择签订公司"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.applyCompany"
            @input="changeCompany"
          ></h-select-company-input>
        </u-form-item>
        <u-form-item label="合同名称" prop="contractId" required>
					<h-select-contract-manager-input
						v-model="model.contractId"
						objectField="model.contractId"
						placeholder="请选择合同编号"
						border="surround"
						:allList="true"
						:status="'2'"
						:muitFlag="true"
						showName="1"
						:multi="true"
						style="width: 100%;"
						:signUnit ="companyVal"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						@detail="contractBack"
					>
					</h-select-contract-manager-input>
        </u-form-item>
        <u-form-item label="是否外带" prop="takeout">
					<h-dict-radio v-model="model.takeout" dictName="yes_no" @input="isGiveBack"></h-dict-radio>
        </u-form-item>
        <u-form-item label="是否归还" prop="giveBack" v-show="model.takeout == '1'">
					<h-dict-radio v-model="model.giveBack" dictName="yes_no" @input="isReturnDate"></h-dict-radio>
        </u-form-item>
        <u-form-item label="借阅日期" prop="borrowDate" required>
          <h-time-select
            mode="date"
            ref="remittanceDate"
            v-model="model.borrowDate"
            placeholder="请选择借阅日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						:minDate="(new Date()).getTime()"
            @change="handleBorrowDateChange"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="预计归还日期" prop="predictReturnDate" required v-if="model.giveBack == '1'">
          <h-time-select
            mode="date"
            ref="predictReturnDate"
            v-model="model.predictReturnDate"
            placeholder="请选择预计归还日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						:minDate="model.borrowDate?(new Date(model.borrowDate)).getTime():315504000000"
						@change="predictReturnDateChange"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="份数" prop="borrowCount">
					<h-number-input placeholder="请输入份数" v-model="model.borrowCount" :digit="0" :min="0"></h-number-input>
        </u-form-item>
        <u-form-item label="借阅事由" prop="borrowCause" required>
          <u--textarea :confirm-type="null" maxlength="500" count placeholder="请输入借阅事由" v-model="model.borrowCause"></u--textarea>
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea :confirm-type="null" maxlength="500" count placeholder="请输入备注" v-model="model.remark"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">申请附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.applyUpload" :isIcon="false"></h-upload-file>
          <file-list v-if="model.applyUpload" v-model="model.applyUpload" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="space-x-1 px-1 btn_position">
				<u-button :disabled="isSubmit" plain type="primary" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit"  type="primary" text="保存并提交" @click="onSubmit" style="margin-left: 40rpx;"></u-button>
      </view>
			<view style="height: 100rpx;"></view>
    </u-form>
	<u-toast ref="uToast"></u-toast>
	<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { validateBlankValue } from '@/utils/utils'
import { gainBillNo, add, info,edit } from '@/api/contract/ErpOmcContractBorrowManagerForm'
import fileList from '@/pages/synergy/components/fileList.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
export default {
  name: 'ErpOmcContractBorrowManagerForm',
  components: { fileList, ProcessNodeConfiguration },
  data() {
    return {
      produceTeamId: '',
      backUpApplicant: '',
      backUpTeamId: '',
      isReset: false,
      resetKey: '',
      index: null,
      showFormModal: false,
      confirmModal: false,
      loading: false,
      companyVal: '-1',
      id: '',
      model: {
        // 基本信息 - 公用
        borrowApplyNo: '',
        createTime: '',
        proposer: '',
        proposerDeptId: '',
        applyCompany: '',
        contractId: '',
				contractName: '',
        takeout: '0',
        giveBack: '0',
        borrowDate: '',
        predictReturnDate: '',
        borrowCount: '',
        borrowCause: '',
        remark: '',
        // 附件
        applyUpload: null,
      },
      formData: [],
      rules: {
        borrowApplyNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
		  
        applyCompany: [{ required: true, message: '请输入签订单位!', trigger: ['blur', 'change'] },],
        applyUser: [{ required: true, message: '请输入申请人!', trigger: ['blur', 'change'] }],
        applyDept: [
          { required: true, message: '请输入申请部门!', trigger: ['blur', 'change'] },
          {
            validator: (rule, value, callback) =>
              validateBlankValue('erp_omc_contract_borrow_manager', 'apply_dept', value, this.model.id, callback),
          },
        ],
        takeout: [
          { required: false, message: '请输入是否外带!', trigger: ['blur', 'change'] },
          {
            validator: (rule, value, callback) =>
              validateBlankValue('erp_omc_contract_borrow_manager', 'takeout', value, this.model.id, callback),
          },
        ],
        contractId: [
          { required: true, message: '请输入合同名称!', trigger: ['blur', 'change'] },
          {
            validator: (rule, value, callback) =>
              validateBlankValue('erp_omc_contract_borrow_manager', 'contract_name', value, this.model.id, callback),
          },
        ],
        borrowDate: [{ required: true, message: '请输入借阅日期!', trigger: ['blur', 'change'] }],
        predictReturnDate: [{ required: true, message: '请选择预计归还日期!', trigger: ['blur', 'change'] }],
        borrowCause: [
          { required: true, message: '请输入借阅事由!', trigger: ['blur', 'change'] },
          {
            validator: (rule, value, callback) =>
              validateBlankValue('erp_omc_contract_borrow_manager', 'borrow_cause', value, this.model.id, callback),
          },
        ],
      },
		isSubmit:false,
		  // 代码生成后需手动设置流程编码
		flowCode: 'dev_erp_omc_contract_borrow_manager_001',
		formUrl: 'erp/omc/contractmanager/modules/ErpOmcContractBorrowManagerForm',
		beanName: 'erpOmcContractBorrowManagerServiceImpl',
		formUrlMobile: '/pages/synergy/erpOmcContractBorrowManagerList',
		processId: ''
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
      this.initBillNo()
    }
  },
  computed: {
    ...mapState(['userInfo']),
    formTotal() {
      return this.formData.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
    },
  },
  methods: {
    changeCompany(val) {
      this.companyVal = val.id
      this.$set(this.model, 'contractId', '')
    },
		
		// 選擇项目名称
		contractBack (item) {
			if (item && item.length) {
				var contractName = []
				for (var i = 0; i < item.length; i++) {
					contractName.push(item[i].htmc);
				}
				this.model.contractName = contractName.join(",");
			}
		},
    // 显示预计归还时间
    isReturnDate(e) {
      if (e == '1') {
        // error
      } else {
        this.model.predictReturnDate = null
      }
    },
    // 显示是否归还
    isGiveBack(e) {
			// this.$set(this.model, 'giveBack', 0)
			this.model.giveBack = '0'
      if (e == '1') {
        this.rules.takeout.required = true
      } else {
        this.rules.takeout.required = true
        this.model.predictReturnDate = null
      }
    },
    handleBorrowDateChange(date, dateStr) {
      this.$set(this.model, 'predictReturnDate', undefined)
      this.predictReturnDate = undefined
    },
		predictReturnDateChange (date, dateStr) {
			if (!this.model.borrowDate) {
				return false
			}
			let isBefore = moment(this.model.borrowDate).isBefore(this.model.predictReturnDate)
			if (!isBefore) {
				const format = 'YYYY-MM-DD'
				const borrowDate = moment(this.model.borrowDate, format)
				const predictReturnDate = moment(this.model.predictReturnDate, format)
				if (borrowDate.isSame(predictReturnDate)) {
					return false
				}
				this.$u.toast('预计归还日期必须大于借阅日期！')
				this.$nextTick(() => {
					this.model.predictReturnDate = null
				})
			}
		},
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ prefix: 'HTJY', subSystemCode: '05' })
      this.model.borrowApplyNo = res.result
      // this.model.bpmBizTitle = this.userInfo.empName + '-' + this.model.borrowApplyNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
      this.model.payee = this.userInfo.empId //领款人
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
			if(data.applyCompany){
				this.companyVal = data.applyCompany
			}
			this.model = Object.assign({}, data)
    },
    resetProject() {},
    resetForm() {},
    validateForm() {
      return this.$refs.form.validate()
    },
    handleTeamChange(item) {
      this.model.teamYear = item.tdnd
    },
    /**
     * 团队变化弹窗点击确认
     */
    handleConfirmModalConfirm() {
      this.formData = []
      this.confirmModal = false
    },
    /**
     * 报销新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
    },
    async onSubmit() {
      await this.validateForm()
	  
	  this.isSubmit = true
	  try {
	    this.loading = true
		var url = ''
		if (this.id) {
			url = edit
		} else {
			url = add
		}
	    const response = await url({
	      ...this.model
	    })
	    this.$u.toast(response.message)
	    if (response.success) {
			var that = this
			
			// 获取流程列表
			if (this.id) {
				this.getProcessList(this.id)
			} else {
			// 判断添加的时候是否有返回id值
				if (response.result) {
					this.getProcessList(response.result)
				}

			}
			this.$refs.uToast.show({
				message: response.message,
				type: 'default',
				complete () {
					// that.isSubmit = false
				}
			})
	    }
	  } finally {
	    // this.loading = false
	  }

    },
    async onDraft() {
      // await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
      var url = ''
      if (this.id) {
        url = edit
      } else {
        url = add
      }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete () {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home'
                })
              }
              
            }
          })
        } else {
          this.isSubmit = false
          this.$refs.uToast.show({
            message: response.message,
            type: 'error'
          })
        }
      } finally {
        this.loading = false
      }
    },
	// 获取流程列表
	getProcessList (id) {
		if (this.isSubmit) {
			this.$refs.processConfig.showPopup = true
			this.$refs.processConfig.formUrl = this.formUrl
			this.$refs.processConfig.formUrlMobile = this.formUrlMobile
			this.$refs.processConfig.flowCode = this.flowCode
			this.$refs.processConfig.edit(id, this.processId, this.beanName)
		}
	},
	// 提交流程成功
	onOk () {
		this.$refs.uToast.show({
			message: '提交成功',
			type: 'success',
			complete () {
				if (getCurrentPages().length > 1) {
					uni.navigateBack()
				} else {
					uni.reLaunch({
						url: '/pages/home/home'
					})
				}
				
			}
		})
	}
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
